package com.cloudbroker.bcs.csvc.itn.facade.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.http.HttpUtils;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.csvc.itn.api.constants.ITNFields;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.cloudbroker.bcs.csvc.itn.api.service.ITNService;

import javax.annotation.Resource;

@Service
public class ITNServiceFacade implements ITNService {
    
    private static final Logger LOG = LoggerFactory.getLogger(ITNServiceFacade.class);
    
    private static final String QRY_AUTHUSER_FUNCTIONID = "100005";
    
    private static final String REG_BIND_FUNCTIONID = "100003";
    
    private static final String SEND_SMS = "101000";
    
    private static final String SEND_MAIL = "101100";
    
    private static final String AUTH_CHECK_CODE = "100158";
    
    private static final String LONG_TOKEN = "100008";
    
    private static final String USER_TOKEN = "100009";
    
    private static final String USER_INFO = "100504";
    
    @Resource
    private ITNT2RemoteService service;
    @Resource
    private ITNT2ProductRemoteService productService;
    
    /**
     * 用户注册与绑定业务账户
     * ITNFields.COMPANY_ID
     * ITNFields.BUSINSYS_NO
     * ITNFields.BUSIN_ACCOUNT
     * ITNFields.MOBILE_TEL
     * ITNFields.LOCK_FLAG
     * ITNFields.REG_SOURCE
     */
    @Override
    public Map<String, Object> registerAuthUser(Map<String, Object> param) {
        param.put(ITNFields.TAG_SUB_SYSTEM_NO, "1");
        return service.callT2(REG_BIND_FUNCTIONID, param);
    }
    
    /**
     * 用登录名AUTH_ID获取
     * ITNFields.AUTH_NAME
     */
    @Override
    public Map<String, Object> qryAuthUser(Map<String, Object> param) {
        param.put(ITNFields.TAG_SUB_SYSTEM_NO, "1");
        return service.callT2(QRY_AUTHUSER_FUNCTIONID, param);
    }
    
    /**
     * ITNFields.TARGETCOMP_ID
     * ITNFields.BUSINSYS_NO
     * ITNFields.USERNAME
     * ITNFields.PASSWORD
     * ITNFields.GRANT_TYPE
     * ITNFields.OPEN_ID
     * @param param
     * @return
     */
    @Override
    public Map<String, Object> createAccessToken(Map<String, Object> param) {
        String authorization = Base64.encodeBase64String((param.get(ITNFields.APP_KEY) + ":" + param
                .get(ITNFields.APP_SECRET)).getBytes());
        Header header = new BasicHeader("Authorization", "Basic " + authorization);
        //Map<String, Object> res = HttpClientUtil.postData(String.valueOf(param.get(ITNFields.URL)), param, header);
        Content content = null;
        try {
            content = Request.Post(String.valueOf(param.get(ITNFields.URL))).connectTimeout(1000)
                    .socketTimeout(2000).bodyForm(HttpUtils.getBuildFormFromMap(param)).addHeader(header).execute()
                    .returnContent();
        } catch (IOException e) {
            return VOUtil.genCommonErrorResult("获取access_token失败");
        }
        String data = null;
        try {
            data = new String(content.asBytes(), "utf-8");
        } catch (UnsupportedEncodingException e) {
        }
        if (StringUtils.isNotEmpty(data)) {
            Map<String, Object> result = JSONObject.parseObject(data);
            return result;
        }
        LOG.warn("获取access_token失败, " + param + " response:" + data);
        return VOUtil.genCommonErrorResult("获取access_token失败");
    }
    
    /**
     * 发送短信
     * ITNFields.MOBILE_TEL
     * ITNFields.SMS_CONTENT
     * ITNFields.OWN_COMPANY_ID
     * ITNFields.COMPANY_ID
     * ITNFields.BUSINSYS_NO
     * ITNFields.SMS_PRIORITY
     * ITNFields.SMS_AUTHKEY
     * @return
     */
    @Override
    public Map<String, Object> sendSms(Map<String, Object> param) {
        param.put(ITNFields.TAG_SUB_SYSTEM_NO, "5");
        return service.callT2(SEND_SMS, param);
    }
    
    @Override
    public Map<String, Object> sendMail(Map<String, Object> param) {
        param.put(ITNFields.TAG_SUB_SYSTEM_NO, "5");
        return service.callT2(SEND_MAIL, param);
    }
    
    /**
     * 获取校验码
     * 邮件校验码有效分钟数30 短信校验码有效分钟数5
     * @param form
     * @return
     *         5103025 认证账户不能为空
     *         5103025 认证信息业务类型不能为空
     *         5103025 认证校验方式不能为空
     *         5103025 电子邮箱不能为空
     *         5103025 手机号码不能为空
     *         5100000 认证信息模板表记录不存在
     *         5100002 增加认证信息表失败
     *         5100005 查询认证信息模板表失败
     *         5100002 增加认证校验表失败
     */
    @Override
    public Map<String, Object> authCheckCode(Map<String, Object> form) {
        //子系统号
        form.put(ITNFields.TAG_SUB_SYSTEM_NO, "1");
        return service.callT2(AUTH_CHECK_CODE, form);
    }
    
    /**
     * 长效令牌获取
     * @param form
     * @return
     *         5103006 认证账户不存在
     *         5103025 认证账户不能为空
     */
    @Override
    public Map<String, Object> getLongToken(Map<String, Object> form) {
        form.put(ITNFields.TAG_SUB_SYSTEM_NO, "1");
        return service.callT2(LONG_TOKEN, form);
    }
    
    /**
     * 手机长效登录
     * @param form
     * @return
     *         5103006 认证账户不存在
     *         5103025 认证账户不能为空
     */
    @Override
    public Map<String, Object> getUserToken(Map<String, Object> form) {
        form.put(ITNFields.TAG_SUB_SYSTEM_NO, "1");
        return service.callT2(USER_TOKEN, form);
    }
    
    /**
     * 从用户中心获取用户信息
     * @param form
     * @return
     *         5100000 认证用户表记录不存在
     *         5103025 认证账户不能为空
     *         5100005 查询认证用户表失败
     */
    @Override
    public Map<String, Object> getItnUserInfo(Map<String, Object> param) {
        param.put(ITNFields.TAG_SUB_SYSTEM_NO, "1");
        param.put(ITNFields.AUTH_ID, param.get("auth_id"));
        return productService.callT2(USER_INFO, param);
    }
}
